<?php
namespace app\common\model\newmodel;

use think\Model;
use think\Db;
use app\common\model\newmodel\UserAgency;
use app\common\model\newmodel\User as UserModel;
use app\common\model\newmodel\Customer;
class Contract extends Model
{
    protected $table = 'product_contract';
    protected $pk = 'id';
    
    /**
     * 关联客户
     */
    public function customer()
    {
        return $this->belongsTo('app\common\model\newmodel\Customer', 'customer_id', 'CustomerId');
    }
    
    /**
     * 获取合同列表（根据用户角色权限）
     */
    public static function getContractList($userId, $page = 1, $pageSize = 10, $keyword = '',$status= '')
    {
        $userInfo = UserModel::get($userId);
        if (!$userInfo) {
            return ['code' => false, 'msg' => '用户不存在'];
        }
        $role = $userInfo->Role;
        
        $query = self::alias('pc')
                    ->where('pc.State',1)
                    ->join('customer c', 'c.CustomerId = pc.customer_id')
                    ->order('pc.create_time desc')
                    ->field('pc.*, c.CustomerId as customer_id, c.UserName as customer_name, c.Tel as customer_phone,c.Name as companyName');
        
        // 业务员 
        if ($role == 201) {
            $query->where('c.LatestAgentId',0);
        } elseif ($role == 401) {
            // 代理商管理员 - 获取同组所有代理商员工
            $agencyId = UserAgency::getAgencyIdByUserId($userId);
            if ($agencyId) {
                $agencyIds = UserAgency::getUserIdsByAgencyId($agencyId);
                $query->whereIn('c.LatestAgentId', $agencyIds);
            } else {
                return ['code' => true, 'msg' => 'success', 'data' => []];
            }
        } elseif ($role == 402) {
            // 代理商员工 - 只能看到自己的
            $query->where('c.LatestAgentId', $userId);
        } else {
            return ['code' => false, 'msg' => '无权限访问合同列表'];
        }
        
        if (!empty($keyword)) {
            $query=$query->where(function ($q) use ($keyword) {
                $q->where('pc.contract_name', 'like', "%{$keyword}%")
                  ->whereOr('c.Name', 'like', "%{$keyword}%")
                  ->whereOr('UserName', 'like', "%{$keyword}%");
            });
        }


        
        if($status !== null){
            $query = $query->where('pc.payment_status', $status);
        }
        $list = $query->paginate([
            'list_rows' => $pageSize,
            'page' => $page,
        ]);

        return ['code' => true, 'msg' => 'success', 'data' => $list];
    }
    
    /**
     * 添加合同
     */
    public static function addContract($data)
    {
    
        if (empty($data['customer_id']) || empty($data['contract_name'])) {
            return ['code' => false, 'msg' => '客户ID和合同名称不能为空'];
        }
        
        $customer = Customer::get($data['customer_id']);
        if (!$customer) {
            return ['code' => false, 'msg' => '客户不存在'];
        }
        $contract = new self();
        $contract->customer_id = $data['customer_id'];
        $contract->contract_name = $data['contract_name'];
        $contract->img_url = $data['img_url'] ?? '';
        $contract->payment_time = $data['payment_time'] ?? null;
        $contract->payment_status = $data['payment_status'] ?? 0;
        $contract->cost = $data['cost'] ?? null;
        $contract->create_time = time();
        $contract->update_time = time();
        $contract->remark = $data['remark'] ?? '';
        $contract->recipient_name = $data['recipient_name'] ?? null;
        $contract->recipient_tel = $data['recipient_tel'] ?? null;
        $contract->recipient_address = $data['recipient_address'] ?? null;

        $contract->is_construction = $data['is_construction'] ?? null;
        $contract->estimated_payment_time = $data['estimated_payment_time'] ?? null;
        $contract->evidence_payment = $data['evidence_payment'] ?? null;
        
        if ($contract->save()) {
            return ['code' => true, 'msg' => '合同添加成功', 'data' => $contract->id];
        } else {
            return ['code' => false, 'msg' => '合同添加失败'];
        }
    }
    
    
    /**
     * 修改合同
     */
    public static function editContract($data)
    {
        if (empty($data['id'])) {
            return ['code' => false, 'msg' => '参数不完整'];
        }
        $contract = self::get($data['id']);
        if (!$contract) {
            return ['code' => false, 'msg' => '合同不存在'];
        }
        $contract->remark = $data['remark'] ?? $contract->remark;
        $contract->payment_status = $data['payment_status'] ?? $contract->payment_status;
        $contract->payment_time = $data['payment_time'] ?? $contract->payment_time;
        $contract->cost = $data['cost'] ?? $contract->cost;
        $contract->img_url = $data['img_url'] ?? $contract->img_url;
        $contract->payment_status = $data['payment_status'] ?? $contract->payment_status;
        $contract->recipient_name = $data['recipient_name'] ?? $contract->recipient_name;
        $contract->recipient_tel = $data['recipient_tel'] ?? $contract->recipient_tel;
        $contract->recipient_address = $data['recipient_address'] ?? $contract->recipient_address;
        $contract->is_construction = $data['is_construction'] ?? $contract->is_construction;
        $contract->estimated_payment_time = $data['estimated_payment_time'] ?? $contract->estimated_payment_time;
        $contract->evidence_payment = $data['evidence_payment'] ?? $contract->evidence_payment;

        if(isset($data['payment_status']) && !$data['payment_status']){
               $contract->payment_time = null;
        }
        $contract->update_time = time();
        if ($contract->save()) {
            return ['code' => true, 'msg' => '修改成功'];
        } else {
            return ['code' => false, 'msg' => '修改失败'];
        }
    } 
}
